import axios from 'axios'
import router from "@/router";
import {message} from "ant-design-vue";

const api = axios.create({
    baseURL: '/api'
})

api.interceptors.request.use(function (config) {
    config.headers.authorization = localStorage.getItem('token') || '';
    return config;
})
api.interceptors.response.use( async function (response) {
    // code为0的提示
    if (response.data.code === 0) {
        message.error(response.data.msg);
        return Promise.reject(response);
    }
    // 处理列表中最后一页数据丢失问题
    if (response.status === 200 && response.data.total > 0 && response.data?.data?.length === 0) {
        return api.request({
            ...response.config,
            params: {
                ...response.config.params,
                pageIndex: response.config.params.pageIndex-1
            }
        });
    }
    return response;
},function ({response}){
    if (response.status === 401) {
        message.error('请重新登录');
        router.push({
            name: 'login',
            query: {
                from: location.pathname
            }
        })
    }
})

export default api;